<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class Sysallme extends Common
{

	//列表
    public function index()
    {

        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $systemNo = $this->request->get('systemNo');
        $systemName = $this->request->get('systemName');

        $this->assign(array('sn'=>$sn));
        $this->assign(array('title'=>$title));
        $this->assign(array('systemNo'=>$systemNo));
        $this->assign(array('systemName'=>$systemName));
        $where = [];
        $where['isdel'] = 0;

        if($sn)
            $where['sn'] = ['like',"%$sn%"];
        if($title)
            $where['title'] = ['like',"%$title%"];
        if($systemNo)
            $where['id'] = ['exp',"in(select jxs from cg_system where sn like '%".$systemNo."%')"];
        if($systemName)
            $where['id'] = ['exp',"in(select jxs from cg_system where title like '%".$systemName."%')"];

        $count = Db::table('cg_jxs')->where($where)->count();
        $data = Db::table('cg_jxs')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
          $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');

            //查询该经销商的所有供货系统
            $systems = Db::table('cg_system t')->join('cg_system_jxs t2','t2.system_id=t.id')->where(['t2.jxs_id'=>$v['id'],'t.isdel'=>0,'t2.isdel'=>0])->field('t.title')->select();
            $temp2 = [];
            foreach($systems as $v1){
                $temp2[] = $v1['title'];
            }
            $data[$k]['systems'] = implode(',',$temp2);

            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch('');
    }

    /**
     * 修改
     * @return mixed
     * @throws \think\Exception
     */
    public function update(){
        $id = $this->request->param('id');

        if($_POST){
            $validate = new Valid([
                'stuff'  => 'require',
                'type'  => 'require',
            ]);
            $data = [];
            $data['stuff'] = $this->request->post('stuff');
            $data['type'] = $this->request->post('type/a');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['stuff'] = explode(',',$data['stuff']);
            $data['stuff'] = serialize($data['stuff']);
            $data['type'] = serialize($data['type']);
            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $bool = Db::table('cg_system_penwarn')->where('id',$id)->update($data);
            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
        }

        //查询未供货系统
        $leftData = Db::table('cg_system')->field('id,title')->where(['isdel'=>0,'id'=>['exp',"in(select system_id from cg_system_jxs where jxs_id <>{$id} and isdel=0)"]])->select();
        $this->assign('leftData',$leftData);

        //现供货系统
        $rightData = Db::table('cg_system')->field('id,title')->where(['isdel'=>0,'id'=>['exp',"in(select system_id from cg_system_jxs where jxs_id ={$id} and isdel=0)"]])->select();
        $this->assign('rightData',$rightData);


        $data = Db::table('cg_jxs')->where('id',$id)->field('id,title')->find();

        $this->assign('data',$data);
        $this->assign('id',$id);

        return $this->fetch('form');
    }

    //    批量设置
    public function batchSet(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }

        //现判断系统里是否有该经销商
        $cnt = Db::table('cg_system_jxs')->where(['jxs_id'=>$pid,'system_id'=>$id])->count();
        if($cnt>0){//有
            $bool = Db::table('cg_system_jxs')->where(['jxs_id'=>$pid,'system_id'=>$id])->update(['isdel'=>0]);//启用该经销商
        }else{//没有
            $bool = Db::table('cg_system_jxs')->insert(['jxs_id'=>$pid,'system_id'=>$id,'cuser'=>Session::get('employee_id'),'ctime'=>time(),'puser'=>Session::get('employee_id'),'ptime'=>time()]);//增加
        }

        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }

    //    批量取消设置经销商
    public function batchSet2(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }

        //
        $default = Db::table('cg_system_jxs')->where(['system_id'=>$id,'jxs_id'=>$pid])->value('default');
        if($default==1){
            echo  json_encode([
                "success"=>false,
                "msg"=>"此经销商是此系统的默认经销商,不能在此移除!"
            ]);die;
        }
        $bool = Db::table('cg_system_jxs')->where(['system_id'=>$id,'jxs_id'=>$pid])->update(['isdel'=>1]);

        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }


    /**
     * 停止供货
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $sys =  Db::table('cg_system_jxs')->where(['jxs_id'=>$id])->select();
        $bool = true;
        foreach($sys as $k=>$v){
            $cnt = Db::table('cg_system_jxs')->where(['system_id'=>$v['system_id']])->count();
            if($cnt<2){
                continue;
            }
            $bool2 = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$v['system_id']])->update(["isdel"=>1]);
            if(false === $bool2){
                $bool = false;
            }
        }

        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"停止成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"停止失败"
            ]);die;
        }
    }

    /**
     * 替换
     * @return mixed
     */
    public function tihuan(){
        $id = $this->request->param('id');

        if($_POST){
            $new1 = $this->request->post('new1');
            if($id==$new1){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"新旧经销商不能一样！"
                ]);
                die;
            }

            //查询新经销商对应的城市省份大区
            $newzpc = Db::table('cg_jxs')->where('id',$new1)->field('city,provice,zoning')->find();

            //查询旧的经销商负责的所有系统
            $syses = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'isdel'=>0])->field('system_id')->select();
            $bool = true;
            foreach($syses as $k=>$v){

                //查询新经销商是否已经存在已选择系统的供货商中
                $cnt = Db::table('cg_system_jxs')->where(['jxs_id'=>$new1,'system_id'=>$v['system_id']])->count();
                if($cnt>0){ //如果已经存在，

                    //先判断旧的是否是默认经销商，如果不是，直接删除旧的，isdel=1
                    $default = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$v['system_id']])->value('default');

                    //还要设置旧的为非默认
                    $b = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$v['system_id']])->update(['isdel'=>1,'default'=>0]);
                    if($b===false)
                        $bool = false;

                    if($default == 1){ //如果是默认经销商，删除旧经销商的同时，并设置新的经销商为默认，并还要修改系统主表的区省市和jxs字段

                        Db::table('cg_system_jxs')->where(['jxs_id'=>$new1,'system_id'=>$v['system_id']])->update(['default'=>1]);

                        //修改系统的默认经销商以及对应的区省市
                        $b = Db::table('cg_system')->where('id',$v['system_id'])->update(['jxs'=>$new1,'city'=>$newzpc['city'],'provice'=>$newzpc['provice'],'zoning'=>$newzpc['zoning']]);
                        if($b===false)
                            $bool = false;
                    }

                }else{//如果不存在，直接用新的替换旧的

                    $b = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$v['system_id']])->update(['jxs_id'=>$new1]);
                    if($b===false)
                        $bool = false;
                    //再查询其是否是默认经销商
                    $default = Db::table('cg_system_jxs')->where(['jxs_id'=>$new1,'system_id'=>$v['system_id']])->value('default');
                    if($default==1){ //是默认经销商
                        //修改系统的默认经销商以及对应的区省市
                        $b = Db::table('cg_system')->where('id',$v['system_id'])->update(['jxs'=>$new1,'city'=>$newzpc['city'],'provice'=>$newzpc['provice'],'zoning'=>$newzpc['zoning']]);
                        if($b===false)
                            $bool = false;
                    }
                }
                //清空本经销商的系统
                $b = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$v['system_id'],'isdel'=>0])->update(['isdel'=>1]);
                if($b===false)
                    $bool = false;
            }

            if(false !== $bool){

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);
            }
            die;
        }

        $this->assign('id',$id);
        $sn = Db::table('cg_jxs')->where('id',$id)->value('sn');
        $this->assign('sn',$sn);
        $title = Db::table('cg_jxs')->where('id',$id)->value('title');
        $this->assign('title',$title);
        $yiyou = Db::table('cg_system t')->field('title')->where(['isdel'=>0,'id'=>['exp',"in(select system_id from cg_system_jxs where jxs_id={$id} and isdel=0)"]])->select();
        foreach($yiyou as $k=>$v){
            $yiyou[$k] = $v['title'];
        }
        $yiyou = implode(',',$yiyou);
        $this->assign('yiyou',$yiyou);

        return $this->fetch();
    }

    /**
     * 追加
     * @return mixed
     */
    public function zhuijia(){
        $id = $this->request->param('id');

        if($_POST){
            $new1 = $this->request->post('new1');
            if($id==$new1){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"新旧经销商不能一样！"
                ]);
                die;
            }


            //查询旧的经销商负责的所有系统
            $syses = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'isdel'=>0])->field('system_id')->select();
            $bool = true;
            foreach($syses as $k=>$v){

                //查询新经销商是否已经存在已选择系统的供货商中
                $cnt = Db::table('cg_system_jxs')->where(['jxs_id'=>$new1,'system_id'=>$v['system_id']])->count();
                if($cnt>0){ //如果已经存在，

                    //直接启用
                    Db::table('cg_system_jxs')->where(['jxs_id'=>$new1,'system_id'=>$v['system_id']])->update(['isdel'=>0]);

                }else{//如果不存在，

                   $b = Db::table('cg_system_jxs')->insert(['jxs_id'=>$new1,'system_id'=>$v['system_id'],'cuser'=>Session::get('employee_id'),'ctime'=>time(),'puser'=>Session::get('employee_id'),'ptime'=>time()]);//追加
                    if(false === $b){
                        $bool = $b;
                    }
                    
                }

            }



            if(false !== $bool){

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"追加成功"
                ]);
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"追加失败"
                ]);
            }
            die;
        }

        $this->assign('id',$id);
        $sn = Db::table('cg_jxs')->where('id',$id)->value('sn');
        $this->assign('sn',$sn);
        $title = Db::table('cg_jxs')->where('id',$id)->value('title');
        $this->assign('title',$title);
        $yiyou = Db::table('cg_system t')->field('title')->where(['isdel'=>0,'id'=>['exp',"in(select system_id from cg_system_jxs where jxs_id={$id} and isdel=0)"]])->select();
        foreach($yiyou as $k=>$v){
            $yiyou[$k] = $v['title'];
        }
        $yiyou = implode(',',$yiyou);
        $this->assign('yiyou',$yiyou);

        return $this->fetch();
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //返回分区经销商树数据
    public function zonetreeajax(){
        $data = Db::table('cg_market_zoning')->where('isdel',0)->field('id,title')->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')->where(array('zoning'=>$v['id']))->field('id,title')->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')->where(array('provice'=>$vv['id']))->field('id,title')->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3['name'] = $v3['title'];
                    //查城市
                    $t3 = Db::table('cg_jxs')->where(array('city'=>$v3['id']))->field('id,title name')->select();//查经销商
                    $temp3['children'] = $t3;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    /**
     * 查询经销商的部分信息
     */
    public function findJxs(){
        $id = $this->request->post('id');
        $data = Db::table('cg_jxs')->where('id',$id)->field('sn,zoning,provice,city')->find();
        $data['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$data['city'])->value('t2.em_name');
        $data['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$data['provice'])->value('t2.em_name');
        $data['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$data['zoning'])->value('t2.em_name');
        echo json_encode($data);die;
    }

    /**
     * 返回经销桑json数据
     */
    public function provicejson(){
        //查询所有省份
        $data = Db::table('cg_jxs')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }


    /**
     * 替换经销商
     * @return mixed
     * @throws \think\Exception
     */
    public function repDealer(){
        if($_POST){
            $data = [];
            $data['zoning'] = $this->request->post('zoning');
            $data['provice'] = $this->request->post('provice');
            $data['city'] = $this->request->post('city');
            $data['jxs'] = $this->request->post('jxs');
            $id = $this->request->param('id');

            $validate = new Valid([
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'jxs'  => 'require',
            ]);


            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $old = Db::table('cg_system')->where('id',$id)->value('jxs');
            $bool = Db::table('cg_system')->where('id',$id)->update($data);
            if(false !== $bool){
                Db::table('cg_system_jxs')->where(['system_id'=>$id,'jxs_id'=>$old,'default'=>1])->update(['jxs_id'=>$data['jxs']]);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);die;
            }
        }
        $zoning = model('Zoning')->select();
        $this->assign('zoning',$zoning);
        return $this->fetch();
    }




}
